package com.lengyu.iottransfer.gateway.file;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class FileUtils {
    public static final String FOLDER_PREFIX="/项目文档/";
    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 在basePath下保存上传的文件夹
     *
     * @param basePath
     * @param files
     */
    public static void saveMultiFile(String basePath, MultipartFile[] files)  {
        if (files == null || files.length == 0) {
            System.out.println("no files uploaded");
            return;
        } else if (files[0].getOriginalFilename() == null || files[0].getOriginalFilename().equals("")) {
            System.out.println("Empty package: no files to be uploaded");
            return;
        }
        if (basePath.endsWith("/")) {
            basePath = basePath.substring(0, basePath.length() - 1);
        }
        for (MultipartFile file : files) {
            //获取上传时的文件名
            String fileName = file.getOriginalFilename();
            String filePath = basePath + "/" + fileName;
            System.out.println("uploading " + fileName + " to " + filePath + "......");
            makeDir(filePath);
            File dest = new File(filePath);
            logger.info("绝对路径" + dest.getAbsolutePath().toString());
            try {
                logger.info("相对路径" + dest.getCanonicalPath().toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                //获取文件的输入流
                InputStream inputStream = file.getInputStream();

                //注意是路径+文件名
                File targetFile = new File(filePath);

                //获取文件的输出流
                OutputStream outputStream = new FileOutputStream(targetFile);
                //最后使用资源访问器FileCopyUtils的copy方法拷贝文件
                FileCopyUtils.copy(inputStream, outputStream);
            } catch (IllegalStateException | IOException e) {
                logger.error("error" , e);
                e.printStackTrace();
            }
        }
    }

    /**
     * 确保目录存在，不存在则创建
     *
     * @param filePath
     */
    private static void makeDir(String filePath) {
        if (filePath.lastIndexOf('/') > 0) {
            String dirPath = filePath.substring(0, filePath.lastIndexOf('/'));
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }
    }
}
